<template>
  <div :class="wrpCls" style="margin-right: 16px">
    <a-space size="middle">
      <a-tooltip>
        <a-input-search
          placeholder="输入电话号码或客户姓名查询"
          style="width: 250px"
          @search="handlefindCustomerByNameOrPhone"
          allow-clear
        />
      </a-tooltip>
      <!-- {{ company }} -->

      <a-tooltip v-if="switchWorkVis">
        <a-button
          v-if="isWorking"
          type="link"
          @click="handleChangeWorking(0)"
          :style="{ fontSize: '16px', color: 'green' }"
        >
          <a-icon type="smile" theme="twoTone" :style="{ fontSize: '20px' }" />
          接单中
        </a-button>
        <a-button
          v-else
          type="link"
          @click="handleChangeWorking(1)"
          :style="{ fontSize: '16px', color: 'red' }"
        >
          <a-icon type="meh" theme="twoTone" :style="{ fontSize: '20px' }" />
          暂停接单中
        </a-button>
      </a-tooltip>

      <a-tooltip v-if="userType === '1' && onLine">
        <template slot="title"> APP在线 </template>
        <a-icon
          type="wechat"
          @click="toConsole"
          :style="{ fontSize: '22px' }"
        />
      </a-tooltip>
      <a-tooltip>
        <a-popover
          title="通知"
          trigger="click"
          placement="bottom"
          :visible="msgVisible"
          @visibleChange="(v) => handleClickChange(v)"
          :overlayStyle="popoverStyle"
        >
          <template #content>
            <!-- 内容区域容器 -->
            <div style="display: flex; flex-direction: column; height: 300px">
              <!-- 列表部分，占据剩余空间 -->
              <a-list
                item-layout="horizontal"
                :data-source="msgList"
                style="flex: 1; overflow-y: auto"
              >
                <a-list-item
                  slot="renderItem"
                  slot-scope="item"
                  style="cursor: pointer"
                  @click="linkTopage(item)"
                >
                  <a-list-item-meta :description="item.content">
                    <!-- 在 title 右上角增加红点 -->
                    <template slot="title">
                      <a-badge :dot="item.isRead === 0">
                        <a>{{ item.msgDesc }}</a>
                      </a-badge>
                    </template>
                  </a-list-item-meta>
                  <div>{{ item.createTime }}</div>
                </a-list-item>
              </a-list>

              <!-- 固定在底部的按钮 -->
              <a-button
                type="link"
                style="
                  text-align: center;
                  padding: 5px;
                  border-top: 1px solid #e8e8e8;
                "
                @click="toMsgPageClick"
              >
                查看全部通知...
              </a-button>
            </div>
          </template>

          <a-badge :dot="dotVisible" style="cursor: pointer">
            <a-icon
              type="sound"
              :style="{ fontSize: '18px' }"
              @click="handlefGetMsgList"
            />
          </a-badge>
        </a-popover>
      </a-tooltip>

      <!-- <a-tooltip @click="toNotice" style="cursor: pointer">
        <template slot="title"> 消息 </template>
        <a-badge :count="msgCount" dot>
          <a-icon type="sound" :style="{ fontSize: '18px' }" />
        </a-badge>
      </a-tooltip> -->
      <!-- <a-tooltip>
        <template slot="title"> 换肤 </template>
        <a-icon
          type="setting"
          @click="showColorSetting()"
          :style="{ fontSize: '18px' }"
        />
      </a-tooltip> -->
      <a-tooltip>
        <template slot="title">
          {{ fullScreen ? "退出全屏" : "切为全屏" }}
        </template>
        <a-icon
          :type="fullScreen ? 'fullscreen-exit' : 'fullscreen'"
          @click="toggleFullScreen"
          :style="{ fontSize: '18px' }"
        />
      </a-tooltip>
      <avatar-dropdown
        :menu="showMenu"
        :current-user="currentUser"
        :class="prefixCls"
      />
      <!-- 暂只支持中文，国际化可自行扩展 -->
      <!-- <select-lang :class="prefixCls" /> -->
    </a-space>
    <platform-version
      v-if="modalVisible"
      ref="platformVersionModal"
      @close="modalVisible = false"
    />
    <a-modal
      title="客户信息"
      :visible="visible"
      width="400px"
      v-if="visible"
      @cancel="handleCancel"
    >
      <a-tabs :default-active-key="activeKey" @change="callback">
        <a-tab-pane
          v-for="customerTab in customerTabs"
          :key="customerTab.id"
          :tab="customerTab.cusName"
        >
          <a-descriptions
            :title="customerTab.cusName"
            :column="1"
            layout="horizontal"
          >
            <a-descriptions-item label="电话">
              {{ customerTab.phone }}
            </a-descriptions-item>
            <a-descriptions-item label="客户来源">
              {{ customerTab.laiyuan }}
            </a-descriptions-item>
            <a-descriptions-item label="客户经理">
              {{ customerTab.userName }}
            </a-descriptions-item>
            <a-descriptions-item label="客户位置">
              <span v-if="customerTab.status == '-1'">线索池</span>
              <span
                v-if="customerTab.status == '0' && customerTab.isHeart == 2"
              >
                重点客户
              </span>
              <span
                v-if="customerTab.status == '0' && customerTab.isHeart !== 2"
              >
                我的客户
              </span>
              <span v-if="customerTab.status == '77' && customerTab.isCj == 1"
                >成交客户</span
              >
              <span v-if="customerTab.status == '7'">公海客户</span>
              <span v-if="customerTab.status == '-3'">黑名单客户</span>
            </a-descriptions-item>
            <a-descriptions-item label="创建时间">
              {{ customerTab.createTime }}
            </a-descriptions-item>
            <a-descriptions-item label="备注">
              {{ customerTab.remark }}
            </a-descriptions-item>
          </a-descriptions>
        </a-tab-pane>
      </a-tabs>

      <template slot="footer">
        <a-button @click="handleCancel">取消</a-button>
        <a-button type="primary" @click="handleOk">确定</a-button>
        <!-- <a-button type="primary" @click="toPage">跳转到列表</a-button> -->
      </template>
    </a-modal>

    <ant-modal
      ref="antModalRef"
      :visible="publishVis"
      modal-title="发现新功能"
      :adjustSize="false"
      :footer="null"
      dialogClass="designer-wrapper"
      @cancel="publishLogCancel"
      modalWidth="600"
      modalHeight="500"
      :modalCutHeight="modalCutHeight"
    >
      <div slot="content">
        <div class="top-box">
          <h2 class="title-h2">{{ publishData.versionNumber }}</h2>

          <h3 class="time-h3">发布时间：{{ publishData.createTime }}</h3>
        </div>
        <div class="weui_article">
          <div class="vditor-preview" style="display: block">
            <div
              class="vditor-reset"
              style="max-width: 100%"
              v-html="publishData.infoHtml"
            ></div>
          </div>
        </div>
      </div>
    </ant-modal>
  </div>
</template>

<script>
import AvatarDropdown from "./AvatarDropdown";
import PlatformVersion from "./PlatformVersion";
import { mapGetters, mapActions } from "vuex";
import { Modal } from "ant-design-vue";
import AntModal from "@/components/pt/dialog/AntModal";
export default {
  name: "RightContent",
  components: {
    AvatarDropdown,
    PlatformVersion,
    AntModal,
  },
  props: {
    prefixCls: {
      type: String,
      default: "ant-pro-global-header-index-action",
    },
    isMobile: {
      type: Boolean,
      default: () => false,
    },
    topMenu: {
      type: Boolean,
      required: true,
    },
    theme: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      customerTabs: [],
      activeKey: "",
      modalVisible: false,
      showMenu: true,
      showPortalDefined: false,
      currentUser: {},
      fullScreen: false,
      msgCount: 0,
      docUrl: "https://docs.geekera.cn/AiDex-Antdv/",
      githubUrl: "https://github.com/fuzui/AiDex-Antdv",
      customer: {},
      visible: false,
      // path: "ws://127.0.0.1:8079",
      // path: "http://47.97.80.183:8077",
      path: "http://47.104.200.227:8079",
      // path: "http://127.0.0.1:8079",
      msg: "",
      audio: new Audio(require("@/assets/sound/newcustomer.wav")),
      xiezuaudio: new Audio(require("@/assets/sound/xiezu.wav")),
      onLine: false,
      toPageUri: "/customer_manage/myindex",
      msgList: [],
      msgVisible: false,
      dotVisible: false,
      isWorking: true,
      switchWorkVis: false,
      publishData: {},
      publishVis: false,
      modalCutHeight: 80,
    };
  },
  computed: {
    wrpCls() {
      return {
        "ant-pro-global-header-index-right": true,
        [`ant-pro-global-header-index-${
          this.isMobile || !this.topMenu ? "light" : this.theme
        }`]: true,
      };
    },
    ...mapGetters([
      "userType",
      "portalConfigs",
      "defaultPortal",
      "sysNoticeList",
      "company",
    ]),
    popoverStyle() {
      return { width: "300px", height: "400px", overflow: "auto" };
    },
    currentUserId() {
      return this.$store.state.user.loginUserId;
    },
  },
  mounted() {
    setTimeout(() => {
      this.currentUser = {
        name: "RuoYi",
      };
    }, 1500);
    this.msgCount = this.sysNoticeList.length;
    this.init();
  },
  created() {
    // setTimeout(() => {
    //   this.$notification.success({
    //     message: "线索通知",
    //     description: `迎回来`,
    //   });
    // }, 1000);
    this.handlefGetMsgList();
    this.handlefGetWorkingStatus();
    // 检查标记是否是登录状态
    if (localStorage.getItem("showPublishDialog") === "true") {
      this.showPublishLog();
      localStorage.removeItem("showPublishDialog");
    }
  },
  methods: {
    callback(key) {
      console.log("Tab changed to:", key);
      const currentTab = this.customerTabs.find((tab) => tab.id === key);
      this.customer = currentTab;
    },
    ...mapActions([
      "GetCustomerByNameOrPhone",
      "GetMsgList",
      "updateBizMessageInfo",
      "listBizPushRuleUser",
      "changeWorkingPushRuleUser",
      "findOneInDays",
    ]),
    // 取消按钮
    publishLogCancel() {
      this.publishVis = false;

      this.$emit("close");
    },
    handlePublishOk(e) {
      this.publishVis = false;
      // const router = "/log/publishLog";
      // this.$router.push({
      //   path: router,
      // });
    },
    showPublishLog() {
      this.findOneInDays().then((response) => {
        if (response.data) {
          this.publishVis = true;
          this.publishData = response.data;
        }
      });
    },

    handlefGetWorkingStatus() {
      const userId = this.company.company.id;
      const ruleUserQueryParam = {
        pageNum: 1,
        pageSize: 10,
        //  isEnable: 1,
        userId: userId,
      };
      // 在规则里的用户才显示订单开关
      this.listBizPushRuleUser(ruleUserQueryParam).then((response) => {
        this.switchWorkVis = response.data.list.length > 0;
        this.isWorking =
          response.data.list.filter((item) => item.isEnable === "1").length > 0;
      });
    },
    handleChangeWorking(isEnable) {
      const des = isEnable === 0 ? "停止" : "开启";
      const changeParam = {
        isEnable: isEnable,
      };
      Modal.confirm({
        title: "提示",
        content: "确定" + des + "接单吗？",
        onOk: () => {
          this.changeWorkingPushRuleUser(changeParam).then((response) => {
            this.isWorking = !this.isWorking;
          });
        },
        onCancel() {},
      });
    },
    handleClickChange(visible) {
      this.msgVisible = visible;
    },
    linkTopage(item) {
      const router = item.router;
      this.msgVisible = false;
      this.$router.push({
        path: router,
      });

      item.isRead = "1";

      const saveForm = JSON.parse(JSON.stringify(item));
      // 修改消息为已读
      this.updateBizMessageInfo(saveForm).then((response) => {
        this.handlefGetMsgList();
      });
    },
    /**
     * 查询消息通知
     */
    handlefGetMsgList() {
      const msgQueryParam = {
        pageNum: 1,
        pageSize: 10,
        status: undefined,
      };
      this.GetMsgList(msgQueryParam).then((response) => {
        this.msgList = response.data.list;
        this.dotVisible =
          this.msgList.filter((item) => item.isRead === 0).length > 0;
      });
    },

    toMsgPageClick() {
      this.msgVisible = false;
      this.$router.push({
        path: "/biz/messageinfo/index",
      });
    },
    /**
     * 查询用户信息
     */
    handlefindCustomerByNameOrPhone(value) {
      console.log("查询客户信息", value);
      if (value) {
        this.GetCustomerByNameOrPhone(value).then((res) => {
          console.log("查询客户信息结果", res);
          if (res.data && res.data.length > 0) {
            this.customerTabs = res.data;
            this.activeKey = this.customerTabs[0].id;
            this.callback(this.activeKey);
            this.visible = true;
          } else {
            this.$message.warning("未查询到数据", 3);
          }
        });
      } else {
        this.$message.warning("请输入电话或姓名", 3);
      }
    },
    handleCancel() {
      this.visible = false;
    },
    handleOk() {
      this.toPage();
    },
    showColorSetting() {
      this.$emit("showSetting");
    },
    toConsole() {
      this.$message.success("尚未实现", 3);
    },
    toNotice() {
      this.$router.push({
        path: "/system/notice/NoticeReadIndex",
      });
      this.msgCount = 0;
    },
    toIndex(item) {
      this.$router.push({
        name: "index",
        params: {
          key: item.id,
        },
      });
      if (item.applicationRange === "U") {
        // 当选中小页时用户自定义时，修改选中小页为默认小页
        this.defaultPortal.id = item.id;
      }
      this.$emit("reloadTab", item);
    },
    toDesignIndex(item, type) {
      this.$message.success("尚未实现", 3);
    },
    toPage() {
      this.visible = false;
      console.log("跳转到列表", this.customer);
      switch (this.customer.status) {
        case "-1":
          this.toPageUri = "/customer_manage/xiansuochi";
          break;
        case "0":
          this.toPageUri = "/customer_manage/myindex";
          if (this.customer.userId !== this.currentUserId) {
            this.toPageUri = "/customer_manage/team_customer";
          } else if (this.customer.isHeart === 2) {
            this.toPageUri = "/customer_manage/zhongdianindex";
          }
          break;
        case "77":
          if (this.customer.isCj === 1) {
            this.toPageUri = "/customer_manage/ok_chengjiao";
          }
          break;
        case "7":
          this.toPageUri = "/customer_manage/public_customer";
          break;
        case "-3":
          this.toPageUri = "/customer_manage/black_customer";
          break;
      }
      this.$router.push({
        path: this.toPageUri,
        query: { phone: this.customer.phone, _t: Date.now() },
      });
    },
    // 全屏切换
    toggleFullScreen() {
      if (!document.fullscreenElement) {
        document.documentElement.requestFullscreen();
      } else {
        if (document.exitFullscreen) {
          document.exitFullscreen();
        }
      }
      this.fullScreen = !this.fullScreen;
    },
    versionInfo() {
      this.modalVisible = true;
      this.$nextTick(() => this.$refs.platformVersionModal.showVersion());
    },
    init: function () {
      if (typeof WebSocket === "undefined") {
        this.$message.error("您的浏览器不支持socket");
      } else {
        // 实例化socket 此处 是登录时存放的 token 和 username
        const userId = this.company.company.id;

        // 拼接 path ： ws://localhost:8866/webSocket/username
        // 如果不需要token验证 则写成
        this.path = this.path.replace("http", "ws");
        this.socket = new WebSocket(this.path + "/websocket/pc/" + userId);
        // 监听socket连接
        this.socket.onopen = this.open;
        // 监听socket错误信息
        this.socket.onerror = this.error;
        // 监听socket消息
        this.socket.onmessage = this.getMessage;
      }
    },
    open: function () {},
    error: function () {},
    getMessage: function (msg) {
      this.handlefGetMsgList();
      var that = this;
      var item = JSON.parse(msg.data);
      var name = "MyIndex";
      if (item.type === "xiezuCus") {
        this.xiezuaudio.play();
        name = "XieZuIndex";
        this.$notification.open({
          message: "消息通知",
          description: item.msg,
          placement: "bottomRight",
          duration: 10,
          icon: function (h) {
            return <a-icon type="message" style="color: #108ee9" />;
          },
          onClick: function () {
            that.$router.push({
              name: name,
            });
          },
          style: "cursor:pointer",
        });
      } else if (item.type === "fenpeiNewCus") {
        this.$notification.open({
          message: "消息通知",
          description: item.msg,
          placement: "bottomRight",
          duration: 10,
          icon: function (h) {
            return <a-icon type="message" style="color: #108ee9" />;
          },
          onClick: function () {
            that.$router.push({
              name: name,
            });
          },
          style: "cursor:pointer",
        });
        this.audio.play();
      } else if (item.type === "onLine") {
        that.onLine = true;
        this.$notification.open({
          message: "消息通知",
          description: "手机APP上线！",
          placement: "bottomRight",
          duration: 10,
          icon: function (h) {
            return <a-icon type="message" style="color: #108ee9" />;
          },
        });
      }
    },
    // 发送消息给被连接的服务端
    send: function (params) {
      this.socket.send(params);
    },
    close: function () {},
    voicePrompt() {
      this.audio.play();
    },
  },
  destroyed() {
    this.socket.onclose = this.close;
  },
};
</script>
<style lang="less" scoped="scoped">
.ant-pro-global-header {
  .anticon {
    vertical-align: middle;
  }
}
.ant-modal-confirm-content {
  p {
    height: 15px;
  }
}
.setUl {
  .ant-dropdown-menu-item {
    padding: 5px 32px;
    font-size: 12px;
  }
  .ant-dropdown-menu-item > .anticon:first-child {
    font-size: 12px;
  }
  .ant-dropdown-menu-item i {
    position: absolute;
    top: 10px;
    font-size: 12px;
    color: #969696;
  }
  .ant-dropdown-menu-item > a.homeTit {
    width: 150px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    color: #333;
  }
  .menu-operation {
    text-align: center;
    i {
      position: relative;
      top: 0px;
      margin-right: 5px;
    }
  }
  .menu-operation:hover {
    i {
      color: #004ca7;
    }
  }
}

.top-box {
  background: #fff;
  margin-bottom: 0px;
  width: 100%;
  padding: 0.5em;
}

.top-box .title-h2 {
  color: #333333;
  font-size: 1.2em;
  text-align: center;
  padding: 0.35em;
  font-weight: bold;
}

.top-box .time-h3 {
  font-size: 0.85em;
  color: #858585;
  text-align: center;
}

.weui_article {
  padding: 0px 15px;
  background: #fff;
  font-size: 1em;
}

.weui_article h2 {
  font-size: 1.1em;
  font-weight: bold;
}
.ant-modal-body {
  padding: 0px !important;
}
</style>
